package cn.edu.sdjzu.xg.kcsj.controller.basic;

import cn.edu.sdjzu.xg.kcsj.domain.DictItem;
import cn.edu.sdjzu.xg.kcsj.domain.Faculty;
import cn.edu.sdjzu.xg.kcsj.exception.BysjException;
import cn.edu.sdjzu.xg.kcsj.service.DictItemService;
import cn.edu.sdjzu.xg.kcsj.service.FacultyService;
import cn.edu.sdjzu.xg.kcsj.util.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Collection;

@WebServlet("/facultyFindAll")
public class FacultyFindAllController extends HttpServlet {
    // 记录器，可以控制日志信息输出到控制台，替代输出语句
    private static final Logger log = LogManager.getLogger(FacultyFindAllController.class);

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 创建JSONObject对象message，以便往前端响应信息
        JSONObject message = new JSONObject();
        // 将request body转换为JSON字串
        String json = JSONUtil.getJSON(request);
        //在数据库表中增加Activity对象
        try {
            // 如果为空直接往前台响应"未收到请求信息"
            if (json == null){
                message.put("message","未收到请求信息");
                log.debug("未收到请求信息");
                // 勿忘在前台输出message
                response.getWriter().println(message);
            }else {
                Collection<Faculty> faculties = FacultyService.getInstance().findAllWithoutElse();
                message.put("data",faculties);
                response.getWriter().println(message);
            }
        } catch (BysjException e) {
            e.printStackTrace();
            message.put("message", "数据库操作异常");
            response.getWriter().println(message);
        } catch (SQLException e) {
            e.printStackTrace();
            message.put("message", "数据库操作异常");
            response.getWriter().println(message);
        } catch (Exception e) {
            e.printStackTrace();
            message.put("message", "网络异常");
            response.getWriter().println(message);
        }
    }
}
